package com.goldze.mvvmhabit.ui.new_ui;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.bumptech.glide.Glide;
import com.goldze.mvvmhabit.BR;
import com.goldze.mvvmhabit.R;
import com.goldze.mvvmhabit.data.DemoRepository;
import com.goldze.mvvmhabit.data.source.HttpDataSource;
import com.goldze.mvvmhabit.data.source.http.service.DemoApiService;
import com.goldze.mvvmhabit.entity.DemoEntity;
import com.goldze.mvvmhabit.entity.NewUiEntity;
import com.goldze.mvvmhabit.ui.network.NetWorkItemViewModel;
import com.goldze.mvvmhabit.ui.network.NetWorkViewModel;
import com.goldze.mvvmhabit.utils.GlideImageLoader;
import com.goldze.mvvmhabit.utils.RetrofitClient;
import com.google.gson.Gson;

import java.io.File;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.ItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.http.upload.ProgressRequestBody;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import okhttp3.MultipartBody;

public class NewUiViewModel extends BaseViewModel<DemoRepository> {
    private MutableLiveData<Integer> uploadProgress = new MutableLiveData<>();
    public SingleLiveEvent<String> uploadEvent = new SingleLiveEvent<>();

    public LiveData<Integer> getUploadProgress() {
        return uploadProgress;
    }

    public ObservableField<DemoEntity.ItemsEntity> entity = new ObservableField<>();

    public ObservableField<String> textContent = new ObservableField<>();

    public class UiChangeLoader {
        //加载更多
        public SingleLiveEvent finishRefreshing = new SingleLiveEvent();
        //加载完成
        public SingleLiveEvent finishLoadmore = new SingleLiveEvent();

    }

    //加载更多
    public BindingCommand onLoadMoreCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

        }
    });
    //刷新
    public BindingCommand onRefreshCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

        }
    });
    //给RecyclerView添加ObservableList
    public ObservableList<ItemNewUiViewModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<ItemNewUiViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_new_ui);

    public NewUiViewModel(@NonNull Application application, DemoRepository demoRepository) {
        super(application, demoRepository);
    }

    public void setTextContent(String textContent) {
        this.textContent.set(textContent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.textContent = null;
    }

    //刷新
    public BindingCommand onClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
//            File file = new File("/storage/emulated/0/Pictures/69db9938f14629e27f7567fdfa830c0.jpg");
//            uploadFile(file);
//            uploadEvent.setValue("");
            uploadEvent.call();
        }
    });

    public void uploadFile(String path) {
        File file = new File(path);
        ProgressRequestBody requestBody = new ProgressRequestBody(file, (progress, total) -> {
            uploadProgress.postValue(progress);
        });

        MultipartBody.Part multipartBody = MultipartBody.Part.createFormData("avatarfile", file.getName(), requestBody);

        DemoApiService apiService = RetrofitClient.getInstance().create(DemoApiService.class);
        apiService.uploadFile(multipartBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        response -> {
                            KLog.i("***返回***");
                            // Handle successful response
                        },
                        error -> {
                            KLog.e("***报错***");
                            // Handle error
                        }
                );
    }

    /**
     * 初始化数据
     */
    public void initData() {
        Long projectId = 7l;
        model.getPersonList(1, 10, 0, projectId)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("请在请求");
                    }
                }).subscribe(new DisposableObserver<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse o) {
                        KLog.i("***获取人员列表***" + new Gson().toJson(o));
                        if (o.isOk() && o.getRows() != null && o.getRows().size() != 0) {
                            for (Object itemsEntity : o.getRows()) {
                                BaseResponse.Row row = (BaseResponse.Row) itemsEntity;
                                if (!StringUtils.isEmpty(row.getAvatorUrl())) {
                                    String resultStr = row.getAvatorUrl().replace("/profile", "https://cs.bdpioneer.com/prod-api/profile");
                                    row.setAvatorUrl(resultStr);
                                }
                                ItemNewUiViewModel itemViewModel = new ItemNewUiViewModel(NewUiViewModel.this, (BaseResponse.Row) itemsEntity);
                                //双向绑定动态添加Item
                                observableList.add(itemViewModel);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //关闭对话框
                        dismissDialog();
                        if (e instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) e).message);
                        }
                    }

                    @Override
                    public void onComplete() {
                        //关闭对话框
                        dismissDialog();
                    }
                });
    }

}
